package com.juzipi.demo.web;


import com.juzipi.demo.pojo.Comment;
import com.juzipi.demo.pojo.User;
import com.juzipi.demo.service.BlogService;
import com.juzipi.demo.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

@Controller
public class CommentController {


    @Autowired
    private CommentService commentService;
    @Autowired
    private BlogService blogService;
    @Value("${comment.avatar}")
    private String avatar;
//    @Value("${comment.author}")
//    private String author;

    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable Long blogId, Model model){
        model.addAttribute("comments",commentService.listCommentByBlogId(blogId));

        return "blog :: commentList";
    }


    @PostMapping("/comments")
    public String post(Comment comment, HttpSession httpSession){
        Long blogId = comment.getBlog().getId();
        comment.setId(blogId);
        comment.setBlog(blogService.getBlog(blogId));
        comment.setAvatar(avatar);
//        comment.setAuthor(author);
        User user = (User) httpSession.getAttribute("user");
        if (user != null){
            comment.setAvatar(user.getAvatar());
            comment.setAdminComment(true);
//            comment.setNickname(user.getNickname());

        }
        else {
            comment.setAvatar(avatar);
        }
        commentService.saveComment(comment);

        return "redirect:/comments/"+ blogId;
    }

}
